package com.wenda.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wenda.dao.ThesisDao;
import com.wenda.entity.Thesis;
import com.wenda.lucene.ThesisIndex;
import com.wenda.service.ThesisService;
@Service("thesisService")
public class ThesisServiceImpl implements ThesisService{
	
	@Autowired
	ThesisDao thesisDao;
	@Resource
	ThesisIndex thesisIndex;
	@Override
	public List<Thesis> findAll() {
		return thesisDao.findAll();
	}
	@Override
	public int checkThesis(String thesisName) throws Exception {
		//与索引库中的论题进行比较
		//1： 可以，-1：不可用，0：待审核
		return thesisIndex.likeThesis(thesisName);
	}
	@Override
	public void insert(Thesis thesis) {
		thesisDao.insertSelective(thesis);
	}
	@Override
	public List<Thesis> findByUserId(Integer id) {
		// TODO Auto-generated method stub
		return thesisDao.findByCreateId(id);
	}
	@Override
	public List<Thesis> findByCollegeId(Integer collegeId) {
		// TODO Auto-generated method stub
		return thesisDao.findByCollegeId(collegeId);
	}
	@Override
	public void updateThesis(Thesis thesis) {
		//判断论题更新级别
		//论题状态：-1：审核失败，0：等待初审，1：初审通过，2：审核通过
		if(thesis.getThesisStatus() == 2){
			//通过主键补全信息
			Thesis temp = thesisDao.findByPrimaryKey(thesis.getThesisId());
			System.out.println(temp);
			//向索引库中添加索引
			try {
				thesisIndex.addIndex(temp);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		//选择性更新数据
		thesisDao.updateSelectiveByPrimaryKey(thesis);
	}
	@Override
	public List<Thesis> findByCollegeWithStatus(Integer collegeId, Integer status) {
		Thesis thesis = new Thesis();
		thesis.setCollegeId(collegeId);
		thesis.setThesisStatus(status);
		return thesisDao.findByCollegeWithStatus(thesis);
	}
	
	/**
	 * 初始化数据库中的所有论文索引
	 */
	@Override
	public String initThesisIndex() {
		List<Thesis> list = thesisDao.findByThesisStatus(2);
		//将审核通过的论文保存至索引库中
		try {
			for (Thesis thesis : list) {
				thesisIndex.addIndex(thesis);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "init failure!!!";
		}
		return "init success!!!";
	}
}
